<?php
namespace org\copperforest\oak\resources\factories;

use \org\copperforest\oak\resources as res;
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class WebResourceFactory extends ResponseFactory
{

    //Cuando lo llama un Collection
    public function fetchArray( $string='', $num = 10, $page = 1, $order = array(), $group = null, &$count=null )
    {
        //Tendría que crear una lista de todos los recursos si me sirviese de algo
        return null;
    }

    public function fetchInstance( $id = null )
    {
        
        //Primero tengo que comprobar el 
        $client_last_modified = isset( $_SERVER[ 'HTTP_HEADERS' ][ 'If-Modified-Since' ]  )? strtotime( trim( $_SERVER[ 'HTTP_HEADERS' ][ 'If-Modified-Since' ] ) ) : 0 ;
        
        if( $_SERVER[ 'CF_TIME' ] <= $client_last_modified ) {
            throw new \org\copperforest\oak\http\exceptions\NotModifiedException();
        }
        
     
        
        //debería obtener la clase de la configurción
        $wri = new $this->authorizedClass();
        //$wri = new res\samples\WebResource();
        $wri->id = $id;
        

        $dir = CF_RESOURCES_PATH ;
       
        
        foreach( $id as $i ){

            if( $i == '..' || $i == '.' ){
                throw new \org\copperforest\oak\http\exceptions\BadRequestException();
            }
            else if(  file_exists ( $dir . $i ) && is_dir( $dir . $i ) ){
                $dir.= $i . DIRECTORY_SEPARATOR;
            }
            else {
                
                if( file_exists ( $dir . $i  ) ) {
                    $wri->files[] = $dir . $i ;
                    $dir = CF_RESOURCES_PATH;
                }
                else{
                    throw new \org\copperforest\oak\http\exceptions\NotFoundException();
                }
            }
            
        }
        
        header( 'Last-Modified:' . gmdate( 'D, d M Y H:i:s',  $_SERVER[ 'CF_TIME' ] ) . ' GMT' );
        header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() +  3600 * 24 ) . ' GMT' ); //Que no nos hagan peticiones al menos en un día
        
        return $wri;
    }

    function parseDataSourceElement( \SimpleXMLElement $xml ){
        return null;
    }
}